package com.hvgroup.modules.sanic.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hvgroup.modules.sanic.service.SSOAuthorizerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class SSOAuthorizerServiceImpl implements SSOAuthorizerService {

    @Value("${oss.base_url}")
    private String baseUrl;
    @Value("${oss.client_id}")
    private String clientId;
    @Value("${oss.client_secret}")
    private String clientSecret;
    @Value("${oss.grant_type}")
    private String grantType;
    @Value("${oss.redirect_url}")
    private String redirectUrl;
    @Override
    public ResponseEntity<Object> getProfile(String code) {



        // 创建参数映射
        Map<String, Object> params = new HashMap<>();
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        params.put("grant_type", grantType);
        params.put("redirect_uri", redirectUrl);
        params.put("code", code);

        HttpResponse response = HttpRequest.post(baseUrl + "accessToken")
                // 自动将参数转换为URL查询字符串
                .form(params)
                // 9秒超时,文档code是10秒失效
                .timeout(10000)
                .execute();

        // 处理响应
        if (response.isOk()) {
            String body1 = response.body();
            JSONObject entries = JSONUtil.parseObj(body1);
            String accessToken = entries.getStr("access_token");
            HttpResponse res = HttpRequest.post(baseUrl+"profile")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .form("access_token", accessToken)
                    .execute();

            // 检查HTTP状态码
            if (!res.isOk()) {
                throw new RuntimeException("IDM接口错误: " + response.getStatus() + " - " + response.body());
            }
            // 解析JSON响应
            String body = res.body();
            return ResponseEntity.ok(body);
        } else {
            System.err.println("请求失败! 状态码: " + response.getStatus());
            return ResponseEntity.badRequest().body(response);
        }

    }
}
